package com.wlbx.agent.ui.activity;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.core.content.FileProvider;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.listener.OnResultCallbackListener;
import com.luck.picture.lib.tools.ToastUtils;
import com.makeramen.roundedimageview.RoundedImageView;
import com.orhanobut.logger.Logger;
import com.wlbx.agent.BuildConfig;
import com.wlbx.agent.R;
import com.wlbx.agent.base.BaseActivity;
import com.wlbx.agent.bean.AccountInfoBean;
import com.wlbx.agent.bean.IncomeBean;
import com.wlbx.agent.event.UpdateUserInfoEvent;
import com.wlbx.agent.global.Constant;
import com.wlbx.agent.net.RequestManager;
import com.wlbx.agent.net.RetrofitCallBack;
import com.wlbx.agent.net.RetrofitRequestInterface;
import com.wlbx.agent.util.Constants;
import com.wlbx.agent.util.FileStorage;
import com.wlbx.agent.util.FileUtil;
import com.wlbx.agent.util.GlideEngine;
import com.wlbx.agent.util.RSAUtils;
import com.wlbx.agent.util.SPUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import cn.jpush.android.api.JPushInterface;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * 个人资料
 */
public class PersonalActivity extends BaseActivity {

    @BindView(R.id.tv_layout_top_back_title)
    TextView mTitleTV;
    @BindView(R.id.iv_layout_top_back)
    ImageView mBackIV;

    @BindView(R.id.riv_header)
    RoundedImageView rivHeader;
    @BindView(R.id.tv_work_no)
    TextView tvWorkNo;
    @BindView(R.id.tv_user_name)
    TextView tvUserName;

    private String mCutPath;


    @Override
    protected int getContentViewId() {
        return R.layout.activity_personal;
    }

    @Override
    public void initEvent() {

    }

    @Override
    public void initData() {
        mTitleTV.setText("个人资料");
        if (!EventBus.getDefault().isRegistered(this))
        {
            EventBus.getDefault().register(this);
        }
        getInfo();

    }

    @OnClick({R.id.iv_layout_top_back,R.id.riv_header})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_layout_top_back:
                finish();
                break;
            case R.id.riv_header:
                showPopupWindow();
                break;
            default:
                break;
        }
    }
    private PopupWindow mPopupWindow;

    private List<LocalMedia> selectList = new ArrayList<>();
    int number;

    private void showPopupWindow() {
        if (mPopupWindow != null && mPopupWindow.isShowing()) {
            mPopupWindow.dismiss();
        } else {
            View view = mInflater.inflate(R.layout.pop_picture_select, null);
            TextView takePhotoTV = view.findViewById(R.id.tv_pop_pictrue_select_take);
            TextView libraryTV = view.findViewById(R.id.tv_pop_pictrue_select_library);
            TextView cancelTV = view.findViewById(R.id.tv_pop_pictrue_select_cancel);
            takePhotoTV.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                        if (ContextCompat.checkSelfPermission(mActivity, Manifest.permission.CAMERA)
                                != PackageManager.PERMISSION_GRANTED) {
                            ActivityCompat.requestPermissions(mActivity, new String[]{Manifest.permission.CAMERA,
                                    Manifest.permission.WRITE_EXTERNAL_STORAGE}, PERMISSION_CAMRA);
                        } else {
                            openCamera();
                        }
                    } else {
                        openCamera();
                    }


                }
            });
            libraryTV.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                        if (ContextCompat.checkSelfPermission(mActivity, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                                != PackageManager.PERMISSION_GRANTED) {
                            ActivityCompat.requestPermissions(mActivity, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE}, PERMISSION_STORAGE);
                        } else {
                            openPicture();
                        }
                    } else {
                        openPicture();
                    }




                }
            });
            cancelTV.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    mPopupWindow.dismiss();
                }
            });
            mPopupWindow = new PopupWindow(view, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
            mPopupWindow.showAtLocation(view, Gravity.NO_GRAVITY, 0, 0);
        }

    }

    private void openPicture() {
        PictureSelector.create(PersonalActivity.this)
                .openGallery(PictureMimeType.ofImage()).selectionMode(PictureConfig.SINGLE)
                .imageEngine(GlideEngine.createGlideEngine())
                .forResult(new OnResultCallbackListener<LocalMedia>() {
                    @Override
                    public void onResult(List<LocalMedia> result) {
                        mPopupWindow.dismiss();
                        Logger.i(JSON.toJSONString(result));
                        for (LocalMedia media:result){
                            String path=media.getRealPath();
                            uploadImg(path);
                        }


                    }

                    @Override
                    public void onCancel() {
                    }
                });

    }

    public static final int PERMISSION_STORAGE = 1000;
    public static final int PERMISSION_CAMRA = 2000;

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case PERMISSION_STORAGE:
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    openPicture();
                } else {
                    ToastUtils.s(mActivity, "未开启手机读写权限，请去设置打开！");
                }
                break;

            case PERMISSION_CAMRA:
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    openCamera();
                } else {
                    ToastUtils.s(mActivity, "未开启手机读写权限，请去设置打开！");
                }
                break;
            default:
                break;
        }
    }

    private void openCamera() {
        PictureSelector.create(PersonalActivity.this)
                .openCamera(PictureMimeType.ofImage()).selectionMode(PictureConfig.SINGLE)
                .imageEngine(GlideEngine.createGlideEngine())
                .forResult(new OnResultCallbackListener<LocalMedia>() {
                    @Override
                    public void onResult(List<LocalMedia> result) {
                        mPopupWindow.dismiss();
                        Logger.i(JSON.toJSONString(result));
                        for (LocalMedia media:result){
                            String path=media.getRealPath();
                            uploadImg(path);
                        }
                    }

                    @Override
                    public void onCancel() {
                        // 取消
                    }
                });
    }

    private void uploadImg(String path) {

        MultipartBody.Builder builder = new MultipartBody.Builder()
                .setType(MultipartBody.FORM);
        File file=new File(path);
        RequestBody body = RequestBody.create(MediaType.parse("multipart/form-data"), file);
        builder.addFormDataPart("files",file.getName(),body);
        List<MultipartBody.Part> parts=builder.build().parts();

        RequestManager
                .mRetrofitManager
                .createRequest(RetrofitRequestInterface.class)
                .uploadHeader(parts)
                .enqueue(new Callback<String>() {
                    @Override
                    public void onResponse(Call<String> call, Response<String> response) {
                              Logger.i(JSON.toJSONString(response));
                              if (response.isSuccessful()){
                                  EventBus.getDefault().post(new UpdateUserInfoEvent());
                              }
                    }

                    @Override
                    public void onFailure(Call<String> call, Throwable t) {
                        Logger.i(t.getMessage());
                    }
                });
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void refreshList(UpdateUserInfoEvent updateUserInfoEvent) {
        getInfo();
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }



    public void getInfo() {
        RequestManager
                .mRetrofitManager
                .createRequest(RetrofitRequestInterface.class)
                .getPersonalInfo()
                .enqueue(new RetrofitCallBack() {

                    @Override
                    public void onSuccess(String response) {
                        Logger.i("event---"+response);
                        JSONObject jsonObject = JSON.parseObject(response);
                        String rCode = jsonObject.getString("code");
                        String rMsg = jsonObject.getString("msg");
                        if ("1000".equals(rCode)) {
                        AccountInfoBean accountInfoBean=JSON.parseObject(response,AccountInfoBean.class);
                            Glide.with(PersonalActivity.this).load(accountInfoBean.getData().getImage()).into(rivHeader);
                            tvWorkNo.setText(accountInfoBean.getData().getWorkNo());
                            tvUserName.setText(accountInfoBean.getData().getName());
//                            SPUtil.putValue(Constant.USER_INFO,Constant.NAME,accountInfoBean.getData().getName());
//                            SPUtil.putValue(Constant.USER_INFO,Constant.IMAGE,accountInfoBean.getData().getImage());
//                            SPUtil.putValue(Constant.USER_INFO,Constant.WORK_NO,accountInfoBean.getData().getWorkNo());
                            JPushInterface.setAlias(getApplicationContext(),0,accountInfoBean.getData().getMobile());

                        }else{
                            Toast.makeText(PersonalActivity.this,rMsg,Toast.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    public void onError(Throwable t) {
                        Logger.i(t.getMessage());

                    }
                });
    }





}